package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
//import com.xuecheng.content.mapper.CourseCategoryMapper;
//import com.xuecheng.content.service.CourseCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        ArrayList<CourseCategoryTreeDto> list = new ArrayList<>();                  //        查询出的列表
        List<CourseCategoryTreeDto> nodes = courseCategoryMapper.selectTreeNodes("1");
        List<CourseCategoryTreeDto> excludeParentNode = nodes.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toList());
//         将每个对象 存入map集合,并去除父节点
        Map<String, CourseCategoryTreeDto> map = excludeParentNode.stream().collect(Collectors.toMap(item -> item.getId(), value -> value, (key1, key2) -> key2));
        excludeParentNode.stream().forEach(item ->{
            Optional.of(item).filter(i -> id.equals(i.getParentid())).ifPresent(list::add);
            Optional.ofNullable(map.get(item.getParentid())).ifPresent(parent -> parent.addChild(item));
        });
        return list;
    }


}